package com.example.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Before("@annotation(com.example.annotation.Log)")
    public void before(){
        System.out.println("before");
    }

    @After("@annotation(com.example.annotation.Log)")
    public void after(){
        System.out.println("after");
    }
    @Around("@annotation(com.example.annotation.Log)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("around");
        //操作人ID - 当前登录员工ID
        //获取请求头当中都jwt令牌,解析获取员工ID
        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //类名
        String className=joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName=joinPoint.getSignature().getName();
        //方法参数
        String methodParams= Arrays.toString(joinPoint.getArgs());

        //调用原始方法执行
        Long begin=System.currentTimeMillis();
        Object result =joinPoint.proceed();
        Long end=System.currentTimeMillis();
        //返回值
        String returnValue= JSONObject.toJSONString(result);
        //执行时间
        Long costTime=end-begin;

        //记录日志
        OperateLog operateLog= new OperateLog(null,
                operateUser, operateTime, className, methodName,
                methodParams, returnValue, costTime);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志:{}", operateLog);
        return result;
    }
}
